package com.zp.mvppractice;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;

import com.github.moduth.blockcanary.BlockCanary;
import com.letv.sarrsdesktop.blockcanaryex.jrt.BlockCanaryEx;
import com.letv.sarrsdesktop.blockcanaryex.jrt.Config;
import com.socks.library.KLog;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
import com.zp.mvppractice.io.DataCenter;


/**
 * Created by izp on 2017/4/6.
 */

public class App extends Application {
    private static App mInstance;
    private RefWatcher refWatcher;
    private static ALog.Builder sBuilder;
    private boolean mIsInSamplerProcess;//判断当前是否在取样线程，取样线程也有可能有app对象？

//    private ActivityStack activitysQueue = ActivityStack.getInstance();
    private ActivityWeakStack activityWeakStack = ActivityWeakStack.getManager();
    private ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
//            activitysQueue.addActivity(activity);//创建
            activityWeakStack.addActivity(activity);
        }
        @Override
        public void onActivityDestroyed(Activity activity) {
//            activitysQueue.popCurrentActivity();// 推出
            activityWeakStack.popCurrentActivity();
        }

        @Override
        public void onActivityStarted(Activity activity) {
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            float rateOfUsed = 1.0f * Runtime.getRuntime().totalMemory() / Runtime.getRuntime().maxMemory();
            KLog.d("totalMemory / maxMemory ：" + rateOfUsed);
            //内存不足时，清空缓存
            if (rateOfUsed > 0.6) {
//                SHAnalyticManager.onEvent("out_of_memory");
//                CacheUtil.clear();
            }

            //退到后台后，清除缓存
//            if (0 >= activityList.size()) {
                KLog.d("app background");
//                CacheUtil.clear();

//                RxBus.getDefault().post(new BackgroundEvent(true));

//            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }
    };
    @Override
    public void onCreate() {
        initBlockCanaryEx();//视力代码中blockCanaryEx的初始化必须在super之前，然后
        super.onCreate();
        mInstance = this;

        initLeakCanary();
        initBlockCanary();
        initLog();
        watchActivityLife();
//        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
    }
    public static App getApp(){
        return mInstance;
    }
    public static Context getAppContext(){
        return mInstance.getApplicationContext();
    }
    private void initBlockCanary(){
        BlockCanary.install(this, new AppBlockCanaryContext());
    }
        private void initBlockCanaryEx(){
        mIsInSamplerProcess = BlockCanaryEx.isInSamplerProcess(this);
        if(!mIsInSamplerProcess) {
            BlockCanaryEx.install(new Config(this));
        }
    }
    public static RefWatcher getRefWatcher(Context context) {
        App application = (App) context.getApplicationContext();
        return application.refWatcher;
    }
    private RefWatcher initLeakCanary() {
        /*
        LeakCanary.install() 会返回一个预定义的 RefWatcher，同时也会启用一个 ActivityRefWatcher，
        用于自动监控调用 Activity.onDestroy() 之后泄露的 activity。
        而观察Fragment需要代码中埋入
        * */
        if (BuildConfig.DEBUG){
            refWatcher = LeakCanary.install(this);
        }else {
            refWatcher = RefWatcher.DISABLED;
        }
        return refWatcher;
    }
    private void initLog(){
        KLog.init(BuildConfig.IS_DEBUG,"vicky");
        ALog.Builder builder = new ALog.Builder(getApp())
                .setLogSwitch(BuildConfig.DEBUG)// 设置log总开关，包括输出到控制台和文件，默认开
                .setConsoleSwitch(BuildConfig.DEBUG)// 设置是否输出到控制台开关，默认开
                .setGlobalTag("vicky")// 设置log全局标签，默认为空
                // 当全局标签不为空时，我们输出的log全部为该tag，
                // 为空时，如果传入的tag为空那就显示类名，否则显示tag
                .setLogHeadSwitch(true)// 设置log头信息开关，默认为开
                .setLog2FileSwitch(false)// 打印log时是否存到文件的开关，默认关
                .setDir("")// 当自定义路径为空时，写入应用的/cache/log/目录中
                .setBorderSwitch(true)// 输出日志是否带边框开关，默认开
                .setConsoleFilter(ALog.V)// log的控制台过滤器，和logcat过滤器同理，默认Verbose
                .setFileFilter(ALog.V);// log文件过滤器，和logcat过滤器同理，默认Verbose
        ALog.d(builder.toString());
    }

    public static DataCenter getDataCenter(){
        return DataCenter.getInstance();
    }

    public LocalBroadcastManager getBroadcast(){
        return  LocalBroadcastManager.getInstance(this);
    }
    public ActivityWeakStack getAppManager(){
        return ActivityWeakStack.getManager();
    }
    private void watchActivityLife(){
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
    }
}
